<template>
	<view class="search">
		<view class="search-item">
			<view class="search-title">
				<view class="f-color">最近搜索</view>
				<uni-icons custom-prefix="iconfont" type="trash-filled" @tap="clearHistory()"></uni-icons>
			</view>
			<view>
				<view v-if="searchData.length>0">
					<view class="search-name f-color" v-for="(item,index) in searchData" :key="index"
						@tap="toSearchList(item)">{{item}}
					</view>
				</view>
				<view class="search-end" v-else>
					暂无搜索记录...
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 搜索的关键词
				keyWord: '',
				// 记录搜索过的词
				searchData: []
			}
		},
		// 页面加载的时候
		onLoad() {
			uni.getStorage({
				key: "searchData",
				success: (res) => {
					this.searchData = JSON.parse(res.data)
				}
			})
		},
		// 监听搜索框输入值的变化
		onNavigationBarSearchInputChanged(e) {
			this.keyWord = e.text
		},
		// 监听原生标题栏按钮点击事件
		onNavigationBarButtonTap(e) {
			if (e.text === "搜索") {
				this.search()

			} else {
				return;
			}
		},
		// 监听软键盘上搜索按钮
		onNavigationBarSearchInputConfirmed() {
			this.search()
		},
		methods: {
			search() {
				if (!this.keyWord) {
					return uni.showToast({
						title: "搜索值不能为空",
						icon: "none"
					})
				} else {
					this.toSearchList(this.keyWord)
				}
				uni.hideKeyboard()
				this.addSearch()
			},
			// 记录搜索词
			addSearch() {
				let idx = this.searchData.indexOf(this.keyWord);
				if (idx < 0) {
					this.searchData.unshift(this.keyWord);
				} else {
					this.searchData.unshift(this.searchData.splice(idx, 1)[0])
				}

				// 将搜索词保存在本地
				uni.setStorage({
					key: "searchData",
					data: JSON.stringify(this.searchData)
				})
			},
			// 清除本地搜索词
			clearHistory() {
				uni.showModal({
					title: "重要提示",
					content: "是否要清楚搜索记录",
					cancelText: "取消",
					confirmText: "确定",
					success: (res) => {
						uni.removeStorage({
							key: "searchData"
						})
						// 清除页面搜索词
						this.searchData = [];
					}
				})
			},
			// 点击搜索记录，进入页面
			toSearchList(item) {
				this.keyWord = item
				this.addSearch()
				uni.navigateTo({
					url: "/pages/search-list/search-list?keyWord=" + item + ""
				})
			}
		}
	}
</script>

<style>
	.search-item {
		padding: 20rpx;
	}

	.search-title {
		display: flex;
		justify-content: space-between;
	}

	.search-name {
		padding: 4rpx 24rpx;
		background-color: #e1e1e1;
		display: inline-block;
		border-radius: 26rpx;
		margin: 10rpx;
	}

	.search-end {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	uni-icons {
		width: 80rpx;
		height: 80rpx;
	}
</style>